import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';

class EncryptUtil {
  /// AES-128-ECB PKCS7 加密
  static String aesEncode({required String key, required String content}) {
    final keyBytes = utf8.encode(key);
    final contentBytes = _pkcs7Pad(Uint8List.fromList(utf8.encode(content)), 16);

    final cipher = ECBBlockCipher(AESEngine())
      ..init(true, KeyParameter(Uint8List.fromList(keyBytes)));

    final encrypted = _processBlocks(cipher, contentBytes);
    return base64Encode(encrypted);
  }

  /// AES-128-ECB PKCS7 解密
  static String aesDecode({required String key, required String content}) {
    final keyBytes = utf8.encode(key);
    final encryptedBytes = base64Decode(content);

    final cipher = ECBBlockCipher(AESEngine())
      ..init(false, KeyParameter(Uint8List.fromList(keyBytes)));

    final decrypted = _processBlocks(cipher, encryptedBytes);
    final unpadded = _pkcs7Unpad(decrypted);
    return utf8.decode(unpadded);
  }

  static Uint8List _processBlocks(BlockCipher cipher, Uint8List input) {
    final output = Uint8List(input.length);
    for (int offset = 0; offset < input.length;) {
      offset += cipher.processBlock(input, offset, output, offset);
    }
    return output;
  }

  static Uint8List _pkcs7Pad(Uint8List data, int blockSize) {
    final pad = blockSize - (data.length % blockSize);
    return Uint8List.fromList([...data, ...List.filled(pad, pad)]);
  }

  static Uint8List _pkcs7Unpad(Uint8List data) {
    final pad = data.last;
    return Uint8List.sublistView(data, 0, data.length - pad);
  }
}
